package com.jinghua.treatment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.jinghua.treatment.entity.*;
import com.jinghua.treatment.entity.vo.DoctorVO;
import com.jinghua.treatment.mapper.*;
import com.jinghua.treatment.service.SysDoctorService;
import com.jinghua.treatment.tools.IDGenerator;
import com.jinghua.treatment.wechat.util.HttpUtil;
import com.jinghua.treatment.wechat.util.WechatUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.transaction.RollbackException;
import java.util.Date;
import java.util.List;

@Service
@Transactional(propagation= Propagation.REQUIRED)
public class SysDoctorServiceImpl implements SysDoctorService {


    @Override
    public SysDoctor findByPhone(String phone) {
        SysDoctor result  = null;
        SysDoctor example  = new SysDoctor();
        example.setPhone(phone);
        List<SysDoctor> sysDoctorList =  sysDoctorMapper.selectByExample(example);
        if(sysDoctorList!=null && sysDoctorList.size()> 0 ){
            result = sysDoctorList.get(0);
        }
        return result;
    }

    @Override
    public SysDoctor regOrLogin(String phone) {
        SysDoctor doctor  = findByPhone( phone);
        if(doctor==null){
            doctor = new SysDoctor();
            doctor.setDoctorCreatedate(new Date());
            doctor.setLastlogindate(new Date());
            doctor.setPhone(phone);
            sysDoctorMapper.insert(doctor);
        }
        return doctor;
    }

    @Override
    @Transactional
    public SysDoctor docRegiste(String phone, String name,String wid) {
        SysDoctor doctor  =  new SysDoctor();
        doctor.setDoctorname(name);
        doctor.setDoctorCreatedate(new Date());
        doctor.setLastlogindate(new Date());
        doctor.setPhone(phone);
        doctor.setIsauthentication(0);


        // 插入医生数据后，再插入一条微信账号数据
        String accessToken = WechatUtil.getAccessToken();
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + wid + "&lang=zh_CN";
        String responseJson = HttpUtil.sendGetRequest(url, null);
        System.out.println("userInfoResponseJson:"+responseJson);
        SysWechatAccount wechatAccount = JSONObject.parseObject(responseJson, SysWechatAccount.class);
        wechatAccount.setUuid(IDGenerator.uuid());

        //获取医生二维码路径，用于医生识别
        String qrUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
        String params = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"#"+wid+"\"}}}";//用于加患者
        String params2 = "{\"action_name\": \"QR_LIMIT_STR_SCENE\", \"action_info\": {\"scene\": {\"scene_str\": \"@"+wid+"\"}}}";//用于发送问诊单
        String qrUrlResponseJson = HttpUtil.sendPostRequest(qrUrl, params);
        String qrUrlResponseJson2 = HttpUtil.sendPostRequest(qrUrl, params2);

        doctor.setWechat(wechatAccount.getOpenid());
        doctor.setSex("0".equals(wechatAccount.getSex())?"女":"男");
        doctor.setPicPath(wechatAccount.getHeadimgurl());
        JSONObject ticketObj = JSONObject.parseObject(qrUrlResponseJson);
        JSONObject ticketObj2 = JSONObject.parseObject(qrUrlResponseJson2);
        //获取医生二维码
        wechatAccount.setQrSceneStr((String)ticketObj.get("ticket"));//用于加患者
        doctor.setQrUrl((String)ticketObj2.get("ticket"));//用于发送问诊单
        sysDoctorMapper.insert(doctor);
        sysWechatAccountMapper.insert(wechatAccount);
        return doctor;
    }

    @Override
    public SysDoctor findById(Integer doctorId) {
        return  sysDoctorMapper.selectByPrimaryKey(doctorId);
    }


    @Override
    @Transactional
    public void saveSertificate(DoctorVO doctorVO) {
        SysDoctor sysDoctor  = new SysDoctor();
        BeanUtils.copyProperties(doctorVO,sysDoctor);
        sysDoctor.setPicPath(doctorVO.getAvatarPath());
        sysDoctor.setDoctorId(doctorVO.getDoctorId());
        sysDoctorMapper.updateByPrimaryKeySelective(sysDoctor);

        SysNotice sysNotice = new SysNotice();
        sysNotice.setSpecialty(doctorVO.getSpecialty());
        sysNotice.setNoticeCreatedate(new Date());
        sysNotice.setDoctorId(sysDoctor.getDoctorId());
        sysNoticeMapper.insert(sysNotice);

        SysAuthentication sysAuthentication  = new SysAuthentication();
        sysAuthentication.setAuthPic(doctorVO.getIdImagePath());
        sysAuthentication.setDoctorId(doctorVO.getDoctorId());
        sysAuthentication.setStatus(1);
        sysAuthentication.setSubmitDate(new Date());
        sysAuthenticationMapper.insert(sysAuthentication);
    }

    @Override
    public int checkAuthStatus(Integer doctorId,HttpSession session) {
        //由于这是进入主页的第一个方法，在这里查出doctor，放入session
       SysDoctor sysDoctor =  sysDoctorMapper.selectByPrimaryKey(doctorId);
       session.setAttribute("currentDoctor",sysDoctor);
       SysAuthentication  sysAuthentication  = sysAuthenticationMapper.selectByDoctorId(doctorId);
       return sysAuthentication == null ? 0: sysAuthentication.getStatus();
    }

    @Override
    public boolean isMyPatient(Integer doctorId, Integer patientId) {
        DPRelationship example  = new DPRelationship();
        example.setDoctorId(doctorId);
        example.setPatientId(patientId);
        List result =  dpRelationshipMapper.selectByExample(example);
        if(result!=null&&result.size()>0)
            return true;
        else
            return false;
    }

    @Resource
    private SysDoctorMapper sysDoctorMapper;

    @Resource
    private SysNoticeMapper sysNoticeMapper;

    @Resource
    private DPRelationshipMapper dpRelationshipMapper;

    @Resource
    private SysAuthenticationMapper sysAuthenticationMapper;

    @Resource
    private SysWechatAccountMapper sysWechatAccountMapper;
}
